package com.fmsz.xmly.activitys;


import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.databinding.DataBindingUtil;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Toast;


import com.fmsz.xmly.R;
import com.fmsz.xmly.application.MyApplication;
import com.fmsz.xmly.callbacks.HttpService;
import com.fmsz.xmly.databinding.ActivityMusicPlayerBinding;
import com.fmsz.xmly.entitys.details.DetailListEntity;
import com.fmsz.xmly.entitys.details.music.MusicEntity;
import com.fmsz.xmly.service.PlayService;
import com.fmsz.xmly.widget.ProgramListPop;

import java.text.SimpleDateFormat;
import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MusicPlayerActivity extends AppCompatActivity implements Callback<MusicEntity>, View.OnClickListener, SeekBar.OnSeekBarChangeListener, CompoundButton.OnCheckedChangeListener {

    private ActivityMusicPlayerBinding binding;
    private PlayService playService;
    private ServiceConnection connection;
    private ProgramListPop pop;
    private DetailListEntity data;
    private int playPosition;
    private SimpleDateFormat format = new SimpleDateFormat("mm:ss");
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            binding.seek.setProgress(msg.arg1/1000);
            timeFormat(msg.arg1);
            switch (msg.what) {
                case 1:
                    ++playPosition;
                    service.getMusicData(data.getData().getTracks().getList().get(playPosition).getTrackId()).enqueue(MusicPlayerActivity.this);
                    break;
            }
        }
    };
    private Call<DetailListEntity> listEntityCall;
    private Call<MusicEntity> musicEntityCall;
    private HttpService service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_music_player);
        Intent intent = getIntent();
        final long trackId = intent.getLongExtra("trackId", -1);
        long albumId = intent.getLongExtra("albumId", -1);
        service = ((MyApplication) getApplication()).getService();
        if (trackId != -1) {
            musicEntityCall = service.getMusicData(trackId);
            musicEntityCall.enqueue(this);
        }
        pop = new ProgramListPop(this, albumId,handler);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                playService = ((PlayService.MyBinder) service).getService();
                playService.setHandler(handler);
            }


            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.i("1620", "onServiceDisconnected: ");
            }
        };
        Intent intent1 = new Intent(this, PlayService.class);
        bindService(intent1, connection, Service.BIND_AUTO_CREATE);
        if (playService == null) {
            startService(intent1);
        }
        listEntityCall = service.getDetailList(String.valueOf(albumId));
        listEntityCall.enqueue(new ProgramListLoad());
        binding.next.setOnClickListener(this);
        binding.preBtn.setOnClickListener(this);
        binding.playOrPause.setOnCheckedChangeListener(this);
        binding.seek.setOnSeekBarChangeListener(this);
        binding.programSelect.setOnClickListener(this);
    }
    

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        unbindService(connection);
        if (listEntityCall.isExecuted()) {
            listEntityCall.cancel();
        }
        if (musicEntityCall.isExecuted()) {
            musicEntityCall.cancel();
        }

    }

    @Override
    public void onResponse(Call<MusicEntity> call, Response<MusicEntity> response) {

        MusicEntity body = response.body();
        if (body != null) {
            binding.setMusicData(body);
            binding.seek.setMax(body.getTrackInfo().getDuration());
            playService.loadMusic(body.getTrackInfo().getPlayUrl32());
        }
    }

    @Override
    public void onFailure(Call<MusicEntity> call, Throwable t) {
        t.printStackTrace();
        Log.i("1620", "onFailure: " + t.getMessage());
        Toast.makeText(this, t.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.preBtn:
                if (playPosition!=0) {
                    --playPosition;
                    service.getMusicData(data.getData().getTracks().getList().get(playPosition).getTrackId()).enqueue(this);
                }
                break;
            case R.id.next:
                ++playPosition;
                service.getMusicData(data.getData().getTracks().getList().get(playPosition).getTrackId()).enqueue(this);
                break;
            case R.id.time_set:
                break;
            case R.id.program_select:
                pop.show();
                break;
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        timeFormat(progress*1000);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int progress = seekBar.getProgress();
        playService.seekToPorgress(progress);

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        playService.pause();
        binding.playOrPause.setBackgroundResource(isChecked ? R.drawable.player_toolbar_pause_normal : R.drawable.player_toolbar_play_normal);
    }


    //service传回的时间格式化
    private void timeFormat(long progress) {
        String time = this.format.format(new Date(progress));
        binding.curTime.setText(time);
    }
    //节目列表下载内部类
    public class ProgramListLoad implements Callback<DetailListEntity>{

        @Override
        public void onResponse(Call<DetailListEntity> call, Response<DetailListEntity> response) {
            DetailListEntity body = response.body();
            if (body!=null) {
                MusicPlayerActivity.this.data = body;
                pop.setData(body);
            }
        }

        @Override
        public void onFailure(Call<DetailListEntity> call, Throwable t) {
            t.printStackTrace();
            Log.i("1620", "onFailure: "+t.getMessage());
            Toast.makeText(MusicPlayerActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}
